<?php

declare(strict_types=1);

namespace App\Controller\admin;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Model\admin\SystemUser;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * @Controller(prefix="admin")
 * Class AuthController
 * @package App\Controller
 */
class PublicController extends AbstractController
{
    /**
     * @RequestMapping(path="login",methods="post")
     */
    public function login(): ResponseInterface
    {
        $credentials = $this->request->inputs(['username','password']);
        $validator = $this->validationFactory->make(
            $credentials,
            [
                'username' => 'required',
                'password' => 'required|min:6'
            ],
            [
                'username.required' => '请输入用户名/手机/邮箱',
                'password.required' => '请输入密码',
                'password.min' => '密码至少6位',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            return $this->fail(ErrorCode::BUSINESS_FAIL,$errorMessage);
        }

        $info = SystemUser::query()->where('username',$credentials['username'])->first();

        if (!$info)
            return $this->fail(ErrorCode::BUSINESS_FAIL,'用户不存在');

        $credentials['password'] .= $info->salt;
        if (!password_verify($credentials['password'],$info['password'])){
            return $this->fail(ErrorCode::BUSINESS_FAIL,'密码不匹配');
        }

        if (!$token = auth()->login($info)) {
            return $this->fail(ErrorCode::TOKEN_INVALID,'Unauthorized');
        }
        $info->update(['login_num'=>$info['login_num'] + 1]);
        return $this->success(['user'=>auth()->user(),'token'=>$token]);
    }

    /**
     * 退出登录
     * @RequestMapping(path="logout",methods="get")
     */
    public function logout(): ResponseInterface
    {
        auth()->logout();
        return $this->success(['msg' => '已退出登录']);
    }
}
